package com.bluesky.ds;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class ReadWriteAspect {

    /**
     * 环绕通知，拦截所有方法上标注有 @ReadWrite注解的方法
     * @param pjp
     * @param readWrite
     * @return
     * @throws Throwable
     */
    @Around(value = "@annotation(readWrite)")
    public Object around(ProceedingJoinPoint pjp, ReadWrite readWrite) throws Throwable{
        // 从threadLocal中获取读写分离策略
        ReadWriteRoutingStrategy strategy = ReadWriteRoutingStrategyHolder.getReadWriteRoutingStrategy();
        //若选择了强制路由到主库，则执行业务
        if(strategy == ReadWriteRoutingStrategy.HIT_MASTER){
            return pjp.proceed();
        }

        //否则 从@ReadWrite注解中获取读写分离策略,放到ThreadLocal中，然后去执行业务
        ReadWriteRoutingStrategyHolder.setReadWriteRoutingStrategy(readWrite.value());
        return pjp.proceed();
    }
}
